﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using System.ComponentModel;
using System.Collections.Specialized;
using System.Collections;
using System.Web;
using Microsoft.SharePoint.Navigation;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint.Utilities;

namespace LanguageConfigurationSolution.LanguageSwitch
{
    public class WSSLanguageSwitch : LanguageSwitchBase
    {

        private void CreateLanguageSwitch(SPWeb web, ref int count)
        {
            bool Supressed = false;
            foreach (object s in Suppress)
            {
                if (s is SuppressWeb)
                {
                    SuppressWeb sw = (SuppressWeb)s;
                    if (sw.Match(web))
                    {
                        Supressed = true;
                        break;
                    }
                }
                else if (s is HtmlGenericControl)
                {
                    throw new Exception("Place runat=\"server\"");
                }
            }

            if (!Supressed)
            {
                if (count == 0)
                {
                    if (HeaderTemplate != null) HeaderTemplate.InstantiateIn(this);
                }
                if (count > 0)
                {
                    if (SeperatorTemplate != null) SeperatorTemplate.InstantiateIn(this);
                }


                LanguageSwitchContainer container = new LanguageSwitchContainer(this, web, null);
                if (CurrentTemplate != null && SPContext.Current.Web.ID.Equals(web.ID))
                {
                    CurrentTemplate.InstantiateIn(container);
                }
                else
                {
                    if (LanguageTemplate != null) LanguageTemplate.InstantiateIn(container);
                }
                Controls.Add(container);
                this.DataBind();

                count++;
            }
        }

        protected override void CreateLanguageSwitches()
        {
            SPSite site = new SPSite(SPContext.Current.Site.ID);

            int count = 0;

            foreach (SPWeb web in site.RootWeb.Webs)
            {
                CreateLanguageSwitch(web, ref count);
            }

            if (count > 0)
            {
                if (FooterTemplate != null) FooterTemplate.InstantiateIn(this);
            }
            else
            {
                if (EmptyTemplate != null) EmptyTemplate.InstantiateIn(this);
            }
        }

    }
}
